package com.csailing4cloud.csailing.common.seicurity.service;

import cn.hutool.core.util.StrUtil;
import com.csailing4cloud.csailing.common.core.util.CsResponse;
import com.csailing4cloud.csailing.common.seicurity.constants.SecurityConstants;
import com.csailing4cloud.csailing.common.seicurity.entity.CsailingUser;
import com.csailing4cloud.csailing.user.api.dto.UserInfo;
import com.csailing4cloud.csailing.user.api.entity.CsUser;
import com.csailing4cloud.csailing.user.api.feign.RemoteUserService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author dyh
 * 用户详细信息
 */
@Slf4j
@Service
@AllArgsConstructor
public class CsailingUserDetailServiceImpl implements CsailingUserDetailsService {

    private final RemoteUserService remoteUserService;
    private final CacheManager cacheManager;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null) {
            return (CsailingUser) cache.get(username).get();
        }

        CsResponse<UserInfo> result = remoteUserService.userInfo(username);
        UserDetails userDetails = getUserDetails(result);
        cache.put(username, userDetails);
        log.info("【loadUserByUsername,userName:{}】",username);
        return userDetails;
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(CsResponse<UserInfo> result) {
        if (result == null || result.getResult() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        CsUser user = result.getResult().getCsUser();
        Set<String> dbAuthsSet = new HashSet<>();
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        boolean enabled = StrUtil.equals(Objects.isNull(user.getLockFlag())?null:String.valueOf(user.getLockFlag()), String.valueOf(SecurityConstants.STATUS_NORMAL));
        // 构造security用户

        return new CsailingUser(user.getId(),  user.getUserName(), SecurityConstants.BCRYPT + user.getPassword(), enabled,
                true, true, !SecurityConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
    }
}
